package com.app.security;

import com.app.config.LoginSuccessHandler;
import com.app.config.LoginfailureHandler;
import com.app.service.authority.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.approval.ApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenApprovalStore;
import org.springframework.security.oauth2.provider.approval.TokenStoreUserApprovalHandler;
import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * security配置
 * 
 * @
 *
 * 2017年2月17日上午11:13:55
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {


	@Autowired
	LoginSuccessHandler loginSuccessHandler;

	@Autowired
	LoginfailureHandler loginfailureHandler;

	@Autowired
	private ClientDetailsService clientDetailsService;

	@Autowired
	private RedisConnectionFactory redisConnection;

	@Bean
	public MyUserDetailsService myUserDetailsService(){
		return new MyUserDetailsService();
	}
	@Autowired
    public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
        auth
			.userDetailsService(myUserDetailsService());
//			.passwordEncoder(new Md5PasswordEncoder());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
		http
		.csrf().disable()
		.anonymous().disable()
		.authorizeRequests()
		.antMatchers("/oauth/**").permitAll();

//		http
//				.csrf().disable()
//				.anonymous().disable()
//				.formLogin()
//				.loginProcessingUrl("/api/login")//指定认证登录URL
//				.usernameParameter("loginname")//username
//				.passwordParameter("password")//password
//				.successHandler(loginSuccessHandler)//认证成功调取
//				.permitAll()
//				.successHandler(loginSuccessHandler) //登录成功后可使用loginSuccessHandler()存储用户信息，可选。
//				.failureHandler(loginfailureHandler)//认证失败调取
//				.and()
//				.logout()
//				.logoutSuccessUrl("/webapp/index.html") //退出登录后的默认网址是”/home”
//				.permitAll()
//				.invalidateHttpSession(true)
//				.and()
//				.authorizeRequests()
//				.antMatchers("/webapp/**.js",
//						"/webapp/**.js.map",
//						"**/**.ico",
//						"**/**.eot",
//						"**/**.woff**",
//						"**/**.eot",
//						"**/**.svg",
//						"**/**.ttf",
//						"**/assets/**",
////						"/api/login/**",
////						"/api/**",
//						"/webapp/#/pages/login",
//						"/webapp/index.html#/pages/login",
//						"/webapp/webapp/index.html#/pages/login",
////						"/test",
//						"/DemoService/post/**/**",
//						"**/favicon.ico")
//				.permitAll()
//				.antMatchers("/**").hasRole("ADMIN")
//				.anyRequest().authenticated();
    }

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


	@Bean
	public TokenStore tokenStore() {
		return new RedisTokenStore(redisConnection);
	}

	@Bean
	@Autowired
	public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
		TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
		handler.setTokenStore(tokenStore);
		handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
		handler.setClientDetailsService(clientDetailsService);
		return handler;
	}
	
	@Bean
	@Autowired
	public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
		TokenApprovalStore store = new TokenApprovalStore();
		store.setTokenStore(tokenStore);
		return store;
	}
	
}
